/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package eu.fastl.dragster.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.fastl.dragster.cache.Cache;
import eu.fastl.dragster.cache.CacheProvider;

/**
 * Servlet Filter for caching response on the Server Side
 *
 * @author Ernst Fastl
 */
public class CacheFilter implements Filter {

	private static final Logger log = LoggerFactory.getLogger(CacheFilter.class);
    private static final String RELOAD_CACHE_ITEM_PARAM = "reloadCacheItem";
    
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        long start = 0;
        long end = 0;
        if (log.isDebugEnabled()) {
            start = System.currentTimeMillis();
    	    log.debug("doFilter... (cachefilter)");
        }
        Cache cache = CacheProvider.getCache();
    	String reloadCacheItem = request.getParameter(RELOAD_CACHE_ITEM_PARAM);
        Object key = CacheKeyGeneratorProvider.getCacheKeyGenerator().createKey(request);
        CachedServletResponse cachedResponse = (CachedServletResponse) cache.get(key);
        CachingServletResponseWrapper cachingServletResponseWrapper = new CachingServletResponseWrapper(response);
        if (cachedResponse == null || reloadCacheItem != null) {
            if( key == null){
                //Key Generator returned null which means that this request should not be cached
                chain.doFilter(request, response);
            } else {
            	chain.doFilter(request, cachingServletResponseWrapper);
                CachingServletOutputStream cachingServletOutputStream = (CachingServletOutputStream)cachingServletResponseWrapper.getOutputStream();
                cachedResponse = new CachedServletResponse(response,cachingServletOutputStream.getCachedContent());
                cache.put(key, cachedResponse);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("cache hit: " + key);
            }
            cachedResponse.writeCachedResponse(response);
        }
        if (log.isDebugEnabled()) {
            end = System.currentTimeMillis();
            log.debug("time needed to handle request: " + (end-start));
        }
    }

    public void destroy() {
    }

}
